package com.itheima.chinamobileai.service;

import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import com.itheima.chinamobileai.po.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.core.io.ClassPathResource;

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.io.InputStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;

@Service
public class RuleVectorService {

    @Autowired
    private VectorStore vectorStore;
    
    // 实现 loadRules 方法
    private List<Rule> loadRules() {
        // 从JSON文件中加载规则
        try {
            ClassPathResource resource = new ClassPathResource("rules.json");
            InputStream inputStream = resource.getInputStream();
            ObjectMapper objectMapper = new ObjectMapper();
            List<Map<String, Object>> rulesData = objectMapper.readValue(inputStream, new TypeReference<List<Map<String, Object>>>() {});
            
            List<Rule> rules = new ArrayList<>();
            for (Map<String, Object> ruleData : rulesData) {
                Rule rule = Rule.builder()
                        .id((String) ruleData.get("id"))
                        .type((String) ruleData.get("type"))
                        .condition((String) ruleData.get("condition"))
                        .description((String) ruleData.get("description"))
                        .build();
                rules.add(rule);
            }
            return rules;
        } catch (Exception e) {
            throw new RuntimeException("Failed to load rules from JSON file", e);
        }
    }
    
    // 初始化规则向量
    @EventListener(ApplicationReadyEvent.class)
    public void initRuleVectors() {
        // 将规则数据转换为向量并存储
        List<Rule> rules = loadRules();
        List<Document> documents = rules.stream()
            .map(rule -> new Document(rule.getDescription(), 
                    Map.of("id", rule.getId(), "type", rule.getType())))
            .collect(Collectors.toList());
        vectorStore.add(documents);
    }

    public List<Rule> searchRelevantRules(String query) {
        // 根据查询内容检索相关规则
        // 使用 SearchRequest.builder() 方法替代直接访问私有方法
        SearchRequest request = SearchRequest.builder()
                .query(query)
                .topK(2)
                .build();
        List<Document> results = vectorStore.similaritySearch(request);
        return results.stream()
            .map(doc -> Rule.builder()
                .id(doc.getMetadata().get("id").toString())
                .type(doc.getMetadata().get("type").toString())
                .description(doc.getText()) // 使用 getText() 方法替代 getContent()
                .build())
            .collect(Collectors.toList());
    }
}